<?php

/***
//应用举例
//创建实例
$DB=new DB('blog.db'); //这个数据库文件名字任意
//创建数据库表。
$DB->query("create table test(id integer primary key,title varchar(50))");
//接下来添加数据
$a = $DB->exec("insert into test(title) values('泡菜')");
var_dump($a);

$DB->query("insert into test(title) values('蓝雨')");
$DB->query("insert into test(title) values('Ajan')");
$DB->query("insert into test(title) values('傲雪蓝天')");
//读取数据
print_r($DB->fetch_arrays('select * from test order by id desc'));

//更新数据， 带返回结果的query
//var_dump($DB->exec('update test set title = "三大" where id = 9'));

/***/

/**
 +------------------------------------------------------------------------------
 * mysqli类 驱动
 +------------------------------------------------------------------------------
 * @version 1.0
 * @author  WangXian
 * @package ephp
 * @filename mysqli.class.php
 * @creation date 2010-8-12
 +------------------------------------------------------------------------------
 */
class db
{
	private $_conn;	#sqlite连接资源文件
	function __construct($db_config='default')
	{
		//加载数据库配置文件
		$config = include APP_PATH . '/conf/db.config.php';
		
		if(false == ( $iconfig = C($db_config, 'db') ) )
		{
			throw new ephpException('数据库配制db.config.php中'.$db_config.'没有配置。', 2001);
		}
		
		//sqlite db full path
		$filename = APP_PATH .'/'. $iconfig['host'];
		//echo $filename;exit;

		if( ! file_exists($filename)) exit('error:your database do not exists, at:'.$filename);

		try
		{
			$this->connection=new PDO('sqlite:'.$filename);
		}
		catch(PDOException $e)
		{
			try
			{
				$this->connection=new PDO('sqlite2:'. $filename);
			}
			catch(PDOException $e)
			{
				exit('can not connect your sqlite db. may be you do not have a sqlite driver.');
			}
		}

	}
	function __destruct()
	{
		$this->connection=null;
	}

	//Executes an SQL statement, returning a result set as a PDOStatement object
	function query($sql) //直接运行SQL，可用于更新、删除数据
	{
		return $this->connection->query($sql);
	}

	//PDO::exec — Execute an SQL statement and return the number of affected rows
	// 带返回结果的query
	function exec($sql)
	{
		return $this->connection->exec($sql);
	}

	function getlist($sql) //取得记录列表
	{
		$recordlist=array();

		$stmt = $this->query($sql);
		$stmt->setFetchMode(PDO::FETCH_ASSOC);

		foreach($stmt as $rstmp)
		{
			$recordlist[]=$rstmp;
		}
		return $recordlist;
	}

	function fetch_array($sql)
	{
		$stmt = $this->query($sql);
		$stmt->setFetchMode(PDO::FETCH_ASSOC);
		return $stmt->fetch();
	}

	function fetch_arrays($sql)
	{
		$stmt = $this->query($sql);
		$stmt->setFetchMode(PDO::FETCH_ASSOC);
		return $stmt->fetchAll();
	}
	
	// 最后更新id
	function insert_id()
	{
		return $this->_conn->lastInsertId();
	}
	// 错误信息
	function errorInfo()
	{
		return $this->_conn->errorInfo();
	}
	function get_error()
	{
		return $this->_conn->errorInfo();
	}
}
?>